package com.atguigu.service;

import com.alibaba.dubbo.config.annotation.Service;

import com.atguigu.constant.RedisConstant;
import com.github.pagehelper.Page;
import com.atguigu.constant.MessageConstant;
import com.atguigu.dao.SetmealDao;
import com.atguigu.entity.PageResult;
import com.atguigu.entity.QueryPageBean;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Setmeal;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisSentinelPool;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;

    @Autowired
    JedisPool jedisPool;
    @Override
    public Result add(Setmeal setmeal, Integer[] travelgroupIds) {
        setmealDao.add(setmeal);
        this.addSetmealAndTravelGroup(setmeal.getId(),travelgroupIds);
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page page = setmealDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> getSetmeal() {
        List<Setmeal> list = setmealDao.getSetmeal();
        return list;
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }

    @Override
    public Setmeal findBysetmealId(Integer id) {
        return setmealDao.findBysetmealId(id);
    }

    @Override
    public List<String> getSetmealname() {
        return setmealDao.getSetmealname();
    }

    @Override
    public List<Map<String, Object>> getSetmealCountByName(List<String> setmealNames) {
        List<Map<String, Object>> list = new ArrayList<>();
        list = setmealDao.getSetmealCountByName();
        return list;
    }

    public void addSetmealAndTravelGroup(Integer id,Integer[] travelgroupIds){
        for (Integer travelgroupId: travelgroupIds) {
            Map<String,Integer> map = new HashMap<String,Integer>();
            map.put("stemealid",id);
            map.put("travelgroupid",travelgroupId);
            setmealDao.addSetmealAndTravelGroup(map);
        }
    }
}
